package com.csi.service.impl;

import com.csi.domain.TravelPackage;
import com.csi.domain.UserBook;
import com.csi.mapper.OrderMapper;
import com.csi.mapper.TravelMapper;
import com.csi.service.OrderService;
import com.csi.service.UserBookService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.*;

@Service
public class UserBookServiceImpl implements UserBookService {

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(100);
    private ConcurrentHashMap<Long, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<>();

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public String saveUserBook(UserBook userBook) {

        synchronized (UserBookServiceImpl.class){

            TravelPackage travelPackage = travelMapper.packageInfo(userBook.getTravelPackageId());

            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

            ops.set("storage"+travelPackage.getId(), String.valueOf(travelPackage.getSurplusPeople()));

            Long res = ops.decrement("storage"+travelPackage.getId(),userBook.getPeopleNum());

            if (res >= 0){

                rabbitTemplate.convertAndSend("userBook.queue",userBook);
                rabbitTemplate.convertAndSend("travelPackage.queue", Map.of("id",travelPackage.getId(),"num",userBook.getPeopleNum()));
                scheduleUnlockTask(userBook);
                return "恭喜你，抢购成功！";
            }

            return "手快有，手慢无啊，多练啊！";
        }
    }

    /**
     * 支付订单
     * @param payId
     * @return
     */
    @Transactional
    @Override
    public int updatedPayOrder(long payId) {
        int updated =  orderMapper.updatedPayOrder(payId);
        scheduledFutures.remove(payId); //将其删除掉
        return updated;
    }

    @Transactional
    public void scheduleUnlockTask(UserBook userBook){
        long delay = 30*60*1000;
        ScheduledFuture<?> future = scheduler.schedule(() ->{
            String payStatus = orderMapper.findPayStatusById(userBook.getId());
            if ("待支付".equals(payStatus)){
                int updated2 = orderMapper.updateCancel(userBook.getId());
                int updated3 = travelMapper.updatedCancel(userBook.getPeopleNum(),userBook.getTravelPackageId());
            }
        },delay, TimeUnit.MILLISECONDS);
        scheduledFutures.put(userBook.getId(),future);
    }
}
